<?php

namespace App\HttpController;

use App\Utility\JwtManager;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\AnnotationController;

abstract class StaffController extends AnnotationController
{
    protected $phone;
    protected $username;
    protected $type;
    protected $sid;
    protected $ip;

    /**
     * @param string|null $action
     * @return bool|null
     */
    protected function onRequest(?string $action): ?bool
    {
        $content = $this->request()->getBody()->__toString();
        $raw_array = json_decode($content, true);
        // 真实IP地址
        $this->ip = ServerManager::getInstance()->getSwooleServer()->connection_info($this->request()->getSwooleRequest()->fd)['remote_ip'];

        // 获取不需要验证的类方法
        $whiteList = []; // token验证白名单 , 值为类方法地址
        $whiteList = [
            'App\HttpController\Index\index',//测试接口
            'App\HttpController\Index\doc',//api文档
            'App\HttpController\Staff\login',//登录接口
        ];

        // 如果访问的类方法不存在于白名单内，验证jwt，默认全部验证
        if (!in_array(static::class . '\\' . $action, $whiteList)) {
            return $this->verifyJWT();
        }

        return true;
    }

    /**
     * 成功返回
     * @param null $result
     * @param string $msg
     * @return bool
     */
    protected function writeJsonSuccess($result = null, string $msg = 'success'): bool
    {
        return $this->writeJson(Status::CODE_OK, $result, $msg);
    }

    /**
     * 错误返回
     * @param string $msg
     * @return bool
     */
    protected function writeJsonError(string $msg = 'error'): bool
    {
        return $this->writeJson(Status::CODE_BAD_REQUEST, null, $msg);
    }

    /**
     * 返回json数据
     * @param int $statusCode
     * @param null $result
     * @param null $msg
     * @return bool
     */
    protected function writeJson($statusCode = 200, $result = null, $msg = null): bool
    {
        return ExceptionHandler::writeJson($this->response(), $statusCode, $result, $msg);
    }

    /**
     * JWT验证
     * @return bool
     */
    protected function verifyJWT(): bool
    {
        $token = $this->request()->getHeader('authorization');

        if (empty($token)) {
            $this->writeJson(403, null, '未找到TOKEN');
            return false;
        }

        $userInfo = JwtManager::getInstance()->decode($token[0]);
        if ($userInfo['code'] !== 200) {
            $this->writeJson(403, null, $userInfo['msg']);
            return false;
        }

        $result = $userInfo['result'];
        $this->sid = $result['uid'];
        $this->phone = $result['userId'];
        $this->username = $result['username'];
        $this->type = $result['type'];

        return true;
    }
}